<template>
  <div style="display: grid; grid-template-columns: 320px auto; grid-column-gap: 20px">
    <div>
      <n-card title="用户组" class="h-full shadow-sm rounded-16px">
        <vxe-grid
          v-bind="userGroupGridOptions"
          :row-config="{ isCurrent: true }"
          @current-change="UserGroupCurrentChangeEvent"
        ></vxe-grid>
      </n-card>
    </div>
    <div>
      <n-card title="权限" class="h-full shadow-sm rounded-16px">
        <template #header-extra>
          <n-form-item label="UI Name" label-placement="left">
            <n-select
              v-model:value="selectedUiName"
              :options="uinameList"
              class="w-40"
              @update:value="handleUpdateUinameValue"
            />
          </n-form-item>
        </template>
        <n-page-header subtitle="赋予权限，其实并不是那么随便">
          <template #title>
            {{ currentUserGroup.userGroupName }}
          </template>
          <template #avatar>
            <n-avatar
              :style="{
                color: 'white',
                backgroundColor: '#3e90ff'
              }"
            >
              <icon-carbon:group-security class="text-2xl hover:text-[#52BF5E]" />
            </n-avatar>
          </template>
        </n-page-header>
        <n-divider />
        <n-spin :show="showLoading">
          <n-tree block-line checkable :checked-keys="checkedKeys" :data="treeData" :node-props="nodeProps" />
          <n-dropdown
            trigger="manual"
            placement="bottom-start"
            :show="showDropdownRef"
            :options="optionsRef as any"
            :x="xRef"
            :y="yRef"
            @select="handleSelect"
            @clickoutside="handleClickoutside"
          />
        </n-spin>
      </n-card>
    </div>
  </div>
</template>
<script setup lang="ts">
import { onMounted, reactive, ref, toRaw } from 'vue';
import type { DropdownOption, SelectOption, TreeOption } from 'naive-ui';
import { useMessage } from 'naive-ui';
import type { VxeGridProps, VxeTableEvents } from 'vxe-table';
import type { Key } from 'naive-ui/es/tree/src/interface';
import {
  fetchDeleteUserGroupMenu,
  fetchInsertUserGroupMenu,
  fetchUseGroupList,
  fetchUserGroupMenuAll
} from '@/service/api/admin';

const selectedUiName = ref('');
const uinameList: Array<SelectOption> = reactive([
  {
    label: 'OIC_LAM',
    value: 'OIC_LAM'
  },
  {
    label: 'REPORT',
    value: 'REPORT'
  }
]);
const treeData = ref<Array<TreeOption>>([]);
const checkedKeys = ref<Key[]>([]);
const message = useMessage();
const currentUserGroup = reactive<Admin.UserGroup>({
  userGroupName: '',
  description: '',
  accessFactory: 'ALL',
  remark: 'ALL'
});
const userGroupGridOptions = reactive<VxeGridProps>({
  border: true,
  maxHeight: 600,
  align: null,
  columnConfig: {
    resizable: true
  },
  columns: [
    { field: 'userGroupName', title: '用户组' },
    { field: 'description', title: '描述', showOverflow: true }
  ],
  data: []
});

const getUserGroupList = async () => {
  const result = await fetchUseGroupList();
  if (result.data) {
    userGroupGridOptions.data = result.data;
  }
};
const buildTreeData = (data: Admin.UserGroupMenu[]) => {
  const treeResult: TreeOption[] = [];
  checkedKeys.value = [];
  // First Level
  data.forEach(element => {
    if (element.superMenuName === null) {
      const level1: TreeOption = { label: element.menuName, key: element.menuName, children: [] };
      treeResult.push(level1);
    }
    if (element.accessFlag !== null) {
      checkedKeys.value.push(element.menuName);
    }
  });
  treeResult.forEach(firstLevel => {
    data.forEach(element => {
      if (firstLevel.label === element.superMenuName) {
        const level2: TreeOption = { label: element.menuName, key: element.menuName, children: [] };
        firstLevel.children?.push(level2);
      }
    });
    firstLevel.children?.forEach(secondLevel => {
      data.forEach(element => {
        if (secondLevel.label === element.superMenuName) {
          const level3: TreeOption = { label: element.menuName, key: element.menuName, isLeaf: true, children: [] };
          secondLevel.children?.push(level3);
        }
      });
    });
  });
  treeData.value = treeResult;
};
const showLoading = ref(false);
const getUserGroupMenuAll = async () => {
  showLoading.value = true;
  const result = await fetchUserGroupMenuAll(selectedUiName.value, currentUserGroup.userGroupName);
  if (result.data) {
    buildTreeData(result.data);
  }
  showLoading.value = false;
};

const UserGroupCurrentChangeEvent: VxeTableEvents.CurrentChange = ({ newValue }) => {
  currentUserGroup.userGroupName = toRaw(newValue).userGroupName;
  currentUserGroup.description = toRaw(newValue).description;
  if (selectedUiName.value !== '') {
    getUserGroupMenuAll();
  }
};
const handleUpdateUinameValue = async () => {
  if (currentUserGroup.userGroupName !== '') {
    getUserGroupMenuAll();
  }
};

const xRef = ref(0);
const yRef = ref(0);
const showDropdownRef = ref(false);
const optionsRef = ref<DropdownOption[]>([
  {
    label: '授权',
    key: '授权'
  },
  {
    label: '取消授权',
    key: '取消授权'
  }
]);
const operateMenuName = ref('');
const handleSelect = async (key: string | number) => {
  showDropdownRef.value = false;
  const userGroupMenu: Admin.UserGroupMenu = {
    uiName: selectedUiName.value,
    userGroupName: currentUserGroup.userGroupName,
    menuName: operateMenuName.value,
    accessFlag: 'W'
  };

  if (String(key) === '授权') {
    const result = await fetchInsertUserGroupMenu(userGroupMenu);
    if (result.data) message.success('处理成功！');
    checkedKeys.value.push(operateMenuName.value);
  } else {
    const result = await fetchDeleteUserGroupMenu(userGroupMenu);
    if (result.data) message.success('处理成功！');
    checkedKeys.value = checkedKeys.value.filter(item => item !== operateMenuName.value);
  }
};

const handleClickoutside = () => {
  showDropdownRef.value = false;
};

const nodeProps = ({ option }: { option: TreeOption }) => {
  return {
    onContextmenu(e: MouseEvent): void {
      e.preventDefault();
      operateMenuName.value = String(option.key);
      if (checkedKeys.value.indexOf(String(option.key)) > 0) {
        optionsRef.value = [
          {
            label: '取消授权',
            key: '取消授权'
          }
        ];
      } else {
        optionsRef.value = [
          {
            label: '授权',
            key: '授权'
          }
        ];
      }
      showDropdownRef.value = true;
      xRef.value = e.clientX;
      yRef.value = e.clientY;
    }
  };
};

onMounted(() => {
  getUserGroupList();
});
</script>
